package dijjer.io.xfer.http.handlers;

import java.io.IOException;
import java.io.OutputStream;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.util.Map;
import dijjer.io.xfer.http.HTTPResponse;
import dijjer.io.xfer.http.PageHandler;
import dijjer.util.logging.Logger;

public class ShutdownHandler extends PageHandler {

	public static final String RCSID = "$Id: ShutdownHandler.java 2 2008-03-21 14:33:03Z ian.clarke $";

	public HTTPResponse handleRequest(String method, String url, Map params, Map headers, Reader in)
	{
		if ("yes".equals(getParam(params, "confirm"))) {
			Logger.info("Shutting down due to request on web interface");
			return new HTTPResponse(HttpURLConnection.HTTP_OK, "Shutting Down", "text/plain") {

				String _output = "Dijjer will now shutdown";

				protected long getContentLength()
				{
					return _output.length();
				}

				protected void writeTo(OutputStream out) throws IOException
				{
					out.write(_output.getBytes());
					out.close(); 
					System.exit(0); // Temporary until Mason can take a look
					/*
					new Thread(new Runnable() {
						public void run() {
							try {
                                new Thread(){
                                    public void run()
                                    {
                                        try {
                                            Thread.sleep(2000);
                                        } catch (InterruptedException e) {
                                            e.printStackTrace();
                                        }
                                        System.exit(945);
                                    }
                                }.start();
								Loader.stopLoader();
							} catch (Exception e) {
								Logger.error(e);
								System.exit(195);
							}
						}
					}).start(); */
				}
			};
		} else {
			return new HTTPResponse(HttpURLConnection.HTTP_BAD_REQUEST, "NOT Shutting Down", "text/plain") {

				String _output = "You must check the Confirm box";

				protected long getContentLength()
				{
					return _output.length();
				}

				protected void writeTo(OutputStream out) throws IOException
				{
					out.write(_output.getBytes());
				}
			};
		}
	}
}
